// utils/api.js
const app = getApp()

class ApiClient {
  constructor() {
    this.baseUrl = app.globalData.baseUrl
  }

  // 通用请求方法
  async request(options) {
    const { url, method = 'GET', data = null, headers = {} } = options
    
    // 添加认证头
    const token = app.globalData.token
    if (token) {
      headers.Authorization = `Bearer ${token}`
    }
    
    // 设置默认头
    headers['Content-Type'] = headers['Content-Type'] || 'application/json'
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.baseUrl}${url}`,
        method,
        data,
        header: headers,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(`HTTP ${res.statusCode}: ${res.data?.message || '请求失败'}`))
          }
        },
        fail: (error) => {
          reject(error)
        }
      })
    })
  }

  // 用户相关API
  user = {
    // 微信登录
    wechatLogin: (code) => this.request({
      url: '/users/wechat-login',
      method: 'POST',
      data: { code }
    }),

    // 获取用户信息
    getProfile: () => this.request({
      url: '/users/me',
      method: 'GET'
    }),

    // 更新用户信息
    updateProfile: (data) => this.request({
      url: '/users/me',
      method: 'PATCH',
      data
    }),

    // 搜索用户
    search: (params) => this.request({
      url: '/users/search',
      method: 'GET',
      data: params
    }),

    // 获取统计数据
    getStats: () => this.request({
      url: '/users/stats',
      method: 'GET'
    }),

    // 上传照片
    uploadPhoto: (filePath) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: `${this.baseUrl}/users/upload-photo`,
          filePath,
          name: 'photo',
          header: {
            Authorization: `Bearer ${app.globalData.token}`
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(JSON.parse(res.data))
            } else {
              reject(new Error('上传失败'))
            }
          },
          fail: reject
        })
      })
    }
  }

  // 匹配相关API
  match = {
    // 获取推荐用户
    getRecommendations: (params) => this.request({
      url: '/matches/recommend',
      method: 'GET',
      data: params
    }),

    // 喜欢用户
    like: (targetUserId) => this.request({
      url: '/matches/like',
      method: 'POST',
      data: { target_user_id: targetUserId }
    }),

    // 获取匹配列表
    getMatches: () => this.request({
      url: '/matches',
      method: 'GET'
    }),

    // 获取喜欢列表
    getLikes: () => this.request({
      url: '/matches/likes',
      method: 'GET'
    }),

    // 获取访客记录
    getVisitors: () => this.request({
      url: '/matches/visitors',
      method: 'GET'
    })
  }

  // 聊天相关API
  chat = {
    // 获取对话列表
    getConversations: () => this.request({
      url: '/chat/conversations',
      method: 'GET'
    }),

    // 获取消息列表
    getMessages: (conversationId, params) => this.request({
      url: '/chat/messages',
      method: 'GET',
      data: { conversation_id: conversationId, ...params }
    }),

    // 发送消息
    sendMessage: (data) => this.request({
      url: '/chat/send',
      method: 'POST',
      data
    }),

    // 标记消息已读
    markAsRead: (conversationId) => this.request({
      url: '/chat/mark-read',
      method: 'POST',
      data: { conversation_id: conversationId }
    })
  }

  // 工具方法
  utils = {
    // 格式化时间
    formatTime: (timestamp) => {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else if (diff < 604800000) { // 1周内
        return `${Math.floor(diff / 86400000)}天前`
      } else {
        return date.toLocaleDateString()
      }
    },

    // 格式化距离
    formatDistance: (distance) => {
      if (distance < 1) {
        return `${Math.round(distance * 1000)}米`
      } else {
        return `${distance.toFixed(1)}公里`
      }
    },

    // 计算年龄
    calculateAge: (birthday) => {
      const birthDate = new Date(birthday)
      const today = new Date()
      let age = today.getFullYear() - birthDate.getFullYear()
      const monthDiff = today.getMonth() - birthDate.getMonth()
      
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--
      }
      
      return age
    },

    // 验证手机号
    validatePhone: (phone) => {
      return /^1[3-9]\d{9}$/.test(phone)
    },

    // 验证邮箱
    validateEmail: (email) => {
      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
    },

    // 防抖函数
    debounce: (func, wait) => {
      let timeout
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout)
          func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
      }
    },

    // 节流函数
    throttle: (func, limit) => {
      let inThrottle
      return function(...args) {
        if (!inThrottle) {
          func.apply(this, args)
          inThrottle = true
          setTimeout(() => inThrottle = false, limit)
        }
      }
    }
  }
}

// 创建单例实例
const apiClient = new ApiClient()

// 导出实例
module.exports = apiClient
